package com.leo.auth.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.leo.auth.entity.Permission;
import com.leo.auth.entity.User;
import com.leo.auth.mapper.PermissionMapper;
import com.leo.auth.mapper.UserMapper;
import com.leo.auth.service.IUserService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.leo.common.security.common.entity.SecurityUser;
import lombok.AllArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.stereotype.Service;
import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 用户 服务实现类
 * </p>
 *
 * @author Leo
 * @since 2021-04-07
 */
@Service
@AllArgsConstructor
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements IUserService, UserDetailsService {
    private final PermissionMapper permissionMapper;

    @Override
    public UserDetails loadUserByUsername(String s) {
        List<GrantedAuthority> grantedAuthorities = new ArrayList<>();
        if (StrUtil.isBlank(s)) {
            throw new RuntimeException("用户名不能为空");
        }
        //根据用户名查询用户
        User user = getOne(Wrappers.lambdaQuery(User.class).eq(User::getUsername, s));
        if (BeanUtil.isEmpty(user)) {
            throw new RuntimeException("用户不存在");
        }else {
            //获取该用户所拥有的权限
            List<Permission> permissions = permissionMapper.selectListByUserId(user.getId());
            // 声明用户授权
            permissions.forEach(permission -> {
                GrantedAuthority grantedAuthority = new SimpleGrantedAuthority(permission.getPermissionCode());
                grantedAuthorities.add(grantedAuthority);
            });
        }
        return new SecurityUser(user.getUsername(), user.getPassword(), user.getEnabled(), user.getAccountNonExpired(),
                user.getCredentialsNonExpired(), user.getAccountNonLocked(), grantedAuthorities);
    }
}
